package com.naiterui.ehp.bs.pharmacist.controller.inner;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

import org.apache.commons.codec.Charsets;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.naiterui.ehp.bp.bo.esign.EsignNoSecretBO;
import com.naiterui.ehp.bp.bo.esign.PreSignResultBO;
import com.naiterui.ehp.bp.constants.SwaggerTag;
import com.naiterui.ehp.bp.support.exception.BaseExceptionCodes;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.support.exception.PublicService;
import com.naiterui.ehp.bp.support.exception.ResponseVO;
import com.naiterui.ehp.bp.utils.lang.ConfigUtil;
import com.naiterui.ehp.bp.utils.lang.StringUtil;
import com.naiterui.ehp.bs.pharmacist.entity.Pharmacist;
import com.naiterui.ehp.bs.pharmacist.exception.ExceptionCodes;
import com.naiterui.ehp.bs.pharmacist.feign.PharmacistEsignFeignClient;
import com.naiterui.ehp.bs.pharmacist.service.IEsignUserService;
import com.naiterui.ehp.bs.pharmacist.service.IPharmacistService;
import com.naiterui.ehp.bs.pharmacist.service.IRecommendService;
import com.naiterui.ehp.bs.pharmacist.vo.user.PharmacistParamVO;

import cn.hutool.json.JSONUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @author guoyongxiang
 * @date 2019/12/4 17:48
 * @since 1.0.0
 */
@Slf4j
@Validated
@RequestMapping("pharmacist/inner/cms")
@RestController
@Api(tags = {SwaggerTag.PHARMACIST + SwaggerTag.INNER_API + SwaggerTag.USER})
public class PharmacistInnerCmsController {

    @Autowired
    private IPharmacistService pharmacistService;
    @Autowired
    private PharmacistEsignFeignClient pharmacistEsignFeginClient;

    @Autowired
    private IEsignUserService userService;

    @Autowired
    private IRecommendService recommendService;

    public static final String HOSPITAL_NAME = ConfigUtil.getString("ehp.hospital.name");

    /**
     * CMS用户信息修改
     */
    @PostMapping("user/update")
    public ResponseVO<Long> update(@RequestHeader String operator,
                                   @Valid @RequestBody PharmacistParamVO paramVO) throws UnsupportedEncodingException, BusinessException {
        log.info("CMS修改药师用户信息 请求参数：operator = {}, paramVO = {}", operator, paramVO);

        String oper = StringUtils.isEmpty(operator) ? "" : URLDecoder.decode(operator, "UTF-8");
        if (paramVO.getId() == null) {
            throw new BusinessException(BaseExceptionCodes.PARAM_ERROR);
        }
        //生成签名图片
//        String sealImage = pharmacistEsignFeginClient.getPersonalSeal(paramVO.getName());
//        paramVO.setSealImage(sealImage);

        Pharmacist pharmacist = pharmacistService.update(oper, paramVO);

        return PublicService.returnResponseVO(pharmacist.getId());
    }

    /**
     * CMS用户新增
     *
     * @param paramVO
     * @return
     */
    @PostMapping("user/add")
    public ResponseVO<Long> add(@RequestHeader String operator,
                                @RequestBody PharmacistParamVO paramVO) throws UnsupportedEncodingException, BusinessException {
        String oper = StringUtils.isEmpty(operator) ? "" : URLDecoder.decode(operator, "UTF-8");
        if (paramVO.getPhone() == null || "".equals(paramVO.getPhone())) {
            throw new BusinessException(ExceptionCodes.SMS_PHONE_NULL);
        }
        if (!StringUtil.isMobileNum(paramVO.getPhone())) {
            throw new BusinessException(ExceptionCodes.SMS_PHONE_ERROR);
        }

        //生成签名图片
        String sealImage = pharmacistEsignFeginClient.getPersonalSeal(paramVO.getName());
        paramVO.setSealImage(sealImage);

        //保存药师
        Pharmacist pharmacist = pharmacistService.add(oper, paramVO);

        return PublicService.returnResponseVO(pharmacist.getId());
    }

    /**
     * 修改药师账户状态 0：默认正常，1：禁用
     *
     * @param pharmacistId
     * @param status
     * @param operator
     * @return
     */
    @GetMapping("/user/{pharmacistId}/{status}")
    public ResponseVO<Void> accountStatus(@PathVariable("pharmacistId") Long pharmacistId,
                                          @PathVariable("status")
                                          @Max(value = 1, message = "状态不正确")
                                          @Min(value = 0, message = "状态不正确") Integer status,
                                          @RequestHeader("operator") String operator) {
        try {
            operator = URLDecoder.decode(operator, Charsets.UTF_8.name());
        } catch (UnsupportedEncodingException ignored) {
        }
        log.info("修改药师禁用状态 请求参数：pharmacistId = {}, status = {} operator = {}", pharmacistId, status, operator);
        pharmacistService.updateAccountStatus(pharmacistId, status, operator);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS);
    }


    @GetMapping("/user/getNoSecret")
    @ApiOperation("获取免密状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pharmacistId", value = "药师id", required = true, dataType = "long")
    })
    public ResponseVO<EsignNoSecretBO> getNoSecret(Long pharmacistId) throws BusinessException {
        log.info("CMS获取免密状态：pharmacistId={}", pharmacistId);
        EsignNoSecretBO noSecretBO = userService.getNoSecretByPharmacistId(pharmacistId);
        log.info("CMS获取免密结果：{}", JSONUtil.toJsonStr(noSecretBO));
        return PublicService.returnResponseVO(noSecretBO);
    }

    @ApiOperation("处方单药师签名预签名")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "处方id", name = "recomId", required = true, dataType = "long"),
            @ApiImplicitParam(value = "药师id", name = "pharmacistId", required = true, dataType = "long")
    })
    @PostMapping("/sign/pre")
    public ResponseVO<PreSignResultBO> preSign(Long recomId, Long pharmacistId) throws BusinessException {
        log.info("获取签名unionId：recomId={}", recomId);
        return PublicService.returnResponseVO(recommendService.getUnionId(recomId, pharmacistId));
    }
}
